/**
 * SubAgentCreator - 4-Step Wizard for Creating Custom Sub-Agents
 * 
 * Step 1: Basic Information (name, description, category, tags)
 * Step 2: System Prompt (visual editor with AI assistance)
 * Step 3: Tools & Model (tool selection, model choice, skills association)
 * Step 4: Review & Save (preview and save configuration)
 */

import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { 
  ChevronLeft, 
  ChevronRight, 
  Check, 
  Sparkles, 
  Code, 
  FileText,
  Settings,
  Save
} from 'lucide-react';

// Sub-Agent Configuration Interface
interface SubAgentConfig {
  id: string;
  name: string;
  description: string;
  prompt: string;
  tools?: string[];
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
  skillIds?: string[];
  category?: string;
  tags?: string[];
}

// Template Interface
interface SubAgentTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  config: Partial<SubAgentConfig>;
}

// Built-in Templates
const BUILTIN_TEMPLATES: SubAgentTemplate[] = [
  {
    id: 'code-reviewer',
    name: 'Code Reviewer',
    description: 'Expert code review specialist',
    category: 'development',
    config: {
      category: 'development',
      tags: ['code-review', 'quality', 'security'],
      model: 'sonnet',
      tools: ['Read', 'Grep', 'Glob'],
    }
  },
  {
    id: 'test-writer',
    name: 'Test Writer',
    description: 'Testing expert for writing unit tests',
    category: 'testing',
    config: {
      category: 'testing',
      tags: ['testing', 'unit-tests', 'tdd'],
      model: 'haiku',
      tools: ['Read', 'Write', 'Bash', 'Grep'],
    }
  },
  {
    id: 'documentation-writer',
    name: 'Documentation Writer',
    description: 'Technical documentation specialist',
    category: 'documentation',
    config: {
      category: 'documentation',
      tags: ['documentation', 'technical-writing'],
      model: 'sonnet',
      tools: ['Read', 'Write', 'Grep', 'Glob'],
    }
  },
];

// Available Tools
const AVAILABLE_TOOLS = [
  'Read', 'Write', 'Bash', 'Grep', 'Glob', 
  'calculator', 'advanced_calculator',
  'read_file', 'write_file', 'list_directory',
  'execute_javascript', 'execute_python', 'execute_shell'
];

// Categories
const CATEGORIES = [
  'development', 'testing', 'security', 'documentation', 
  'analysis', 'optimization', 'design', 'other'
];

export function SubAgentCreator({ onSave, onCancel }: {
  onSave: (config: SubAgentConfig) => void;
  onCancel: () => void;
}) {
  const [currentStep, setCurrentStep] = useState(1);
  const [config, setConfig] = useState<Partial<SubAgentConfig>>({
    model: 'sonnet',
    category: 'development',
    tags: [],
    tools: [],
    skillIds: [],
  });

  // Step 1: Basic Information
  const renderStep1 = () => (
    <div className="space-y-6">
      <div>
        <h3 className="text-lg font-semibold mb-4">选择模板（可选）</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {BUILTIN_TEMPLATES.map((template) => (
            <Card 
              key={template.id}
              className="cursor-pointer hover:border-primary transition-colors"
              onClick={() => setConfig({ ...config, ...template.config })}
            >
              <CardHeader>
                <CardTitle className="text-sm">{template.name}</CardTitle>
                <CardDescription className="text-xs">{template.description}</CardDescription>
              </CardHeader>
              <CardContent>
                <Badge variant="secondary">{template.category}</Badge>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>

      <div className="space-y-4">
        <div>
          <Label htmlFor="name">名称 *</Label>
          <Input
            id="name"
            placeholder="例如: Code Reviewer"
            value={config.name || ''}
            onChange={(e) => setConfig({ ...config, name: e.target.value })}
          />
        </div>

        <div>
          <Label htmlFor="description">描述 *</Label>
          <Textarea
            id="description"
            placeholder="描述 sub-agent 的功能和使用场景..."
            value={config.description || ''}
            onChange={(e) => setConfig({ ...config, description: e.target.value })}
            rows={3}
          />
          <p className="text-xs text-muted-foreground mt-1">
            Claude 会根据这个描述决定何时调用此 sub-agent
          </p>
        </div>

        <div>
          <Label htmlFor="category">分类</Label>
          <select
            id="category"
            className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"
            value={config.category || 'development'}
            onChange={(e) => setConfig({ ...config, category: e.target.value })}
          >
            {CATEGORIES.map((cat) => (
              <option key={cat} value={cat}>{cat}</option>
            ))}
          </select>
        </div>

        <div>
          <Label htmlFor="tags">标签（用逗号分隔）</Label>
          <Input
            id="tags"
            placeholder="例如: code-review, quality, security"
            value={config.tags?.join(', ') || ''}
            onChange={(e) => setConfig({ 
              ...config, 
              tags: e.target.value.split(',').map(t => t.trim()).filter(Boolean)
            })}
          />
        </div>
      </div>
    </div>
  );

  // Step 2: System Prompt
  const renderStep2 = () => (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Label htmlFor="prompt">系统提示词 *</Label>
        <Button variant="outline" size="sm">
          <Sparkles className="w-4 h-4 mr-2" />
          AI 生成
        </Button>
      </div>
      <Textarea
        id="prompt"
        placeholder="定义 sub-agent 的角色、专长和行为..."
        value={config.prompt || ''}
        onChange={(e) => setConfig({ ...config, prompt: e.target.value })}
        rows={15}
        className="font-mono text-sm"
      />
      <div className="flex items-center justify-between text-xs text-muted-foreground">
        <span>{config.prompt?.length || 0} 字符</span>
        <span>建议: 200-400 字</span>
      </div>
    </div>
  );

  // Step 3: Tools & Model
  const renderStep3 = () => (
    <div className="space-y-6">
      <div>
        <Label>模型选择</Label>
        <div className="grid grid-cols-4 gap-2 mt-2">
          {(['sonnet', 'opus', 'haiku', 'inherit'] as const).map((model) => (
            <Button
              key={model}
              variant={config.model === model ? 'default' : 'outline'}
              onClick={() => setConfig({ ...config, model })}
              className="capitalize"
            >
              {model}
            </Button>
          ))}
        </div>
      </div>

      <div>
        <Label>工具选择（可选）</Label>
        <p className="text-xs text-muted-foreground mb-2">
          不选择则继承所有可用工具
        </p>
        <div className="grid grid-cols-3 gap-2 max-h-60 overflow-y-auto p-2 border rounded-md">
          {AVAILABLE_TOOLS.map((tool) => (
            <label key={tool} className="flex items-center space-x-2 cursor-pointer">
              <input
                type="checkbox"
                checked={config.tools?.includes(tool)}
                onChange={(e) => {
                  const tools = config.tools || [];
                  setConfig({
                    ...config,
                    tools: e.target.checked
                      ? [...tools, tool]
                      : tools.filter(t => t !== tool)
                  });
                }}
                className="rounded border-gray-300"
              />
              <span className="text-sm">{tool}</span>
            </label>
          ))}
        </div>
      </div>
    </div>
  );

  // Step 4: Review & Save
  const renderStep4 = () => (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>配置预览</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label className="text-muted-foreground">名称</Label>
            <p className="font-medium">{config.name}</p>
          </div>
          <div>
            <Label className="text-muted-foreground">描述</Label>
            <p className="text-sm">{config.description}</p>
          </div>
          <div>
            <Label className="text-muted-foreground">分类</Label>
            <Badge variant="secondary">{config.category}</Badge>
          </div>
          <div>
            <Label className="text-muted-foreground">标签</Label>
            <div className="flex flex-wrap gap-1 mt-1">
              {config.tags?.map((tag) => (
                <Badge key={tag} variant="outline">{tag}</Badge>
              ))}
            </div>
          </div>
          <div>
            <Label className="text-muted-foreground">模型</Label>
            <p className="font-medium capitalize">{config.model}</p>
          </div>
          <div>
            <Label className="text-muted-foreground">工具</Label>
            <p className="text-sm">
              {config.tools?.length ? `${config.tools.length} 个工具` : '继承所有工具'}
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );

  const steps = [
    { number: 1, title: '基本信息', icon: FileText, render: renderStep1 },
    { number: 2, title: '系统提示', icon: Code, render: renderStep2 },
    { number: 3, title: '工具 & 模型', icon: Settings, render: renderStep3 },
    { number: 4, title: '审查 & 保存', icon: Check, render: renderStep4 },
  ];

  const currentStepData = steps[currentStep - 1];
  const isLastStep = currentStep === steps.length;
  const isFirstStep = currentStep === 1;

  const canProceed = () => {
    if (currentStep === 1) return config.name && config.description;
    if (currentStep === 2) return config.prompt;
    return true;
  };

  const handleSave = () => {
    const finalConfig: SubAgentConfig = {
      id: config.name?.toLowerCase().replace(/\s+/g, '-') || '',
      name: config.name || '',
      description: config.description || '',
      prompt: config.prompt || '',
      model: config.model,
      tools: config.tools?.length ? config.tools : undefined,
      skillIds: config.skillIds?.length ? config.skillIds : undefined,
      category: config.category,
      tags: config.tags,
    };
    onSave(finalConfig);
  };

  return (
    <div className="max-w-4xl mx-auto p-6">
      {/* Progress Steps */}
      <div className="mb-8">
        <div className="flex items-center justify-between">
          {steps.map((step, index) => {
            const Icon = step.icon;
            const isActive = currentStep === step.number;
            const isCompleted = currentStep > step.number;
            
            return (
              <React.Fragment key={step.number}>
                <div className="flex flex-col items-center">
                  <div className={`
                    w-10 h-10 rounded-full flex items-center justify-center
                    ${isActive ? 'bg-primary text-primary-foreground' : ''}
                    ${isCompleted ? 'bg-green-500 text-white' : ''}
                    ${!isActive && !isCompleted ? 'bg-muted text-muted-foreground' : ''}
                  `}>
                    {isCompleted ? <Check className="w-5 h-5" /> : <Icon className="w-5 h-5" />}
                  </div>
                  <span className="text-xs mt-2">{step.title}</span>
                </div>
                {index < steps.length - 1 && (
                  <div className={`flex-1 h-0.5 mx-2 ${isCompleted ? 'bg-green-500' : 'bg-muted'}`} />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Step Content */}
      <Card>
        <CardHeader>
          <CardTitle>{currentStepData.title}</CardTitle>
        </CardHeader>
        <CardContent>
          {currentStepData.render()}
        </CardContent>
        <CardFooter className="flex justify-between">
          <Button
            variant="outline"
            onClick={() => isFirstStep ? onCancel() : setCurrentStep(currentStep - 1)}
          >
            <ChevronLeft className="w-4 h-4 mr-2" />
            {isFirstStep ? '取消' : '上一步'}
          </Button>
          <Button
            onClick={() => isLastStep ? handleSave() : setCurrentStep(currentStep + 1)}
            disabled={!canProceed()}
          >
            {isLastStep ? (
              <>
                <Save className="w-4 h-4 mr-2" />
                保存
              </>
            ) : (
              <>
                下一步
                <ChevronRight className="w-4 h-4 ml-2" />
              </>
            )}
          </Button>
        </CardFooter>
      </Card>
    </div>
  );
}

